class Solution:
    def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
        up, down, left, right = 0, len(matrix), 0, len(matrix[0])
        i, j, flag = 0, 0, 0
        res = []
        for _ in range(down * right):
            if flag == 0:  # 左到右
                res.append(matrix[i][j])
                j += 1
                if j == right:
                    j -= 1
                    flag = 1
                    i += 1
                    up += 1
            elif flag == 1:  # 上到下
                res.append(matrix[i][j])
                i += 1
                if i == down:
                    i -= 1
                    flag = 2
                    j -= 1
                    right -= 1
            elif flag == 2:  # 右到左
                res.append(matrix[i][j])
                if j == left:
                    i -= 1
                    flag = 3
                    down -= 1
                    continue
                j -= 1
            elif flag == 3:  # 下到上
                res.append(matrix[i][j])
                if i == up:
                    j += 1
                    flag = 0
                    left += 1
                    continue
                i -= 1

        return res
